<?php

/**
 * Project:  JWPlayer Time Slider Tooltip Plugin: Contact Sheet Creator for PHP
 * File:     ContactSheet.class.php
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @author Thure Fransen <thure dot fransen at gmail dot com>
 * @requires ffmpeg & php imagick
 */

  ini_set('max_execution_time', 0);

  $contactsheet = new ContactSheet('111.mp4');
  $contactsheet->convert();

  class ContactSheet {
    function __construct($video) {
      $this->video    = $video;
      $this->name     = substr($video,0,-4);
      $this->duration = $this->getDuration();
    }

    function convert() {
      for($j=1;$j<=$this->duration;$j=$j+25) {
        $this->createSheet($j, $int, $z++);
      }
    }

    function createSheet($j, $i, $y) {
      $im = new Imagick();
      $row = new Imagick();

      for($x=$j;$x<$j+25;$x++) {
        try {
          $im->readImage($img = $this->extractImage($x));
          $im->setImageCompression(imagick::COMPRESSION_JPEG);
          $im->setImageCompressionQuality(20);
          unlink($img);
        } catch(Exception $e) { $last = true; }

        if(!($x%5) || $last) {
          $im->resetIterator();
          $row->addImage($im->appendImages(false));
          $im = new Imagick();
        }
      }
      $row->resetIterator();
      $combined = $row->appendImages(true);
      $combined->setImageCompression(imagick::COMPRESSION_JPEG);
      $combined->setImageCompressionQuality(20);
      $combined->stripImage();
      $combined->writeImage(sprintf("%s_%04d.jpg", $this->name, $y));
    }

    function extractImage($sec) {
      exec(sprintf("ffmpeg -ss %d -i %s -threads 0 -vframes 1 -vf scale=108:60 -f image2 %s_%05d.png 2>&1", $sec, $this->video, $this->name, $sec));
      return sprintf("%s_%05d.png", $this->name, $sec);
    }

    function getDuration() {
      exec("ffmpeg -i \"{$this->video}\" 2>&1", $rs);
      preg_match('/Duration: (.*?),/', implode(' ',$rs), $duration);
      $time = explode(':', $duration[1]);
      return floor(($time[0]*3600)+($time[1]*60)+$time[2]);
    }
  }